const express = require('express'),
  router = express.Router(),
  role = require("../model/role"),
  roleauth = require("../model/roleauth"),
  async = require('async'),
  util = require("../util/util");


/**
 * @function 增加角色
 * @author Eric
 * @date 2017-11-9
 * @param roleid,rolename,comment
 */
router.post('/add', function (req, res) {
    const newObj = new role(req.body);
    let roleid = req.body.roleid || util.randomString(6)
    let rolename=req.body.rolename
    newObj.roleid=roleid;
    let params = {
        roleid: roleid,
        rolename: rolename
    }
    if (rolename) {
        role.find(params, (err, results) => {
            if (err) {
                res.send(util.reObj(-1, 'failed', err))
            } else {
                if (results.length > 0) {
                    res.send(util.reObj(-2, 'exist'))
                } else {
                    newObj.save((err, result) => {
                        if (err) {
                            res.send(util.reObj(-1, '添加角色失败'))
                        } else {
                            res.send(util.reObj(0, '添加角色成功', result))
                        }
                    })
                }
            }
        })
    }
    else
    {
        res.send(util.reObj(-1, '角色名称不能为空'))
    }

})

/**
 * @function 修改角色信息
 * @author qiwen
 * @date 2017-11-9
 * @param roleid,appid,orgtype,rolename,,comment
 */
router.post('/edit', function (req, res) {
  let roleid = req.body.roleid
  let rolename = req.body.rolename
  let comment = req.body.comment
  let params = {
    roleid: roleid,
  }

  let updateparams = {
    rolename: rolename,
    comment: comment
  }
  //去掉空的属性
  for (var key of Object.keys(updateparams)) {
    if (!updateparams[key])
      delete updateparams[key]
  }
    role.findOneAndUpdate(params,updateparams,(err,results)=>{
        if(err)
        {
            res.send(util.reObj(-1,'修改角色失败',err))
        }
        else
        {
            res.send(util.reObj(0,'修改角色成功',results))
        }
    })

})

/**
 * @function 删除角色数据
 * @author qiwen
 * @date 2017-11-9
 * @param roleid
 */
router.post('/del', function (req, res) {
  let roleid = req.body.roleid
    let params = {
        roleid: roleid
    }
    role.deleteMany(params,(err,result)=>{
        if (err) {
            res.send(util.reObj(-1,'删除权限失败'))
        }
        else {
            if(result>0)
            {
                res.send(util.reObj(0,'删除权限成功'))
            }
            else
            {
                res.send(util.reObj(0,'删除权限失败或此记录不存在'))
            }
        }
    })
})


/**
 * @function 获取所有角色数据
 * @author Eric
 * @date 2018-05-28
 * @param orgtype,appid （可选）
 */
router.post('/getrolelist', async function (req, res) {
    let param={},
    skipnum=req.body.skipnum||0,
    pagesize=req.body.pagesize||100;
    try {
        const results = await role.find(param,null,{skip: parseInt(skipnum), limit:parseInt(pagesize),sort: {created_time: -1}})
        //const results = await role.find(param,null,{skip:parseInt(skipnum-1)*pagesize, limit:parseInt(pagesize),sort: {created_time: -1}})
        const count =await role.count({})
        res.send(util.reObj("0",'success',results,count))
    }
    catch (err) {
        res.send(util.reObj(-1,'failed',err))
    }
})

/**
 * @function 获取角色数据
 * @author siwei
 * @date 2018-08-08
 * @param roleid
 */
router.post('/getroleinfo', function (req, res) {
  let params = {
    roleid: req.body.roleid
  }
  role.find({where: params}).then(record => {
    if (record) {
        res.send(util.reObj(0, '获取角色信息成功', record))
    } else {
        res.send(util.reObj(-1, '获取角色信息失败或此记录不存在'))
    }
  }).catch(err => {

      res.send(util.reObj(-1, '获取角色信息失败', err))
  });
});

/**
 * @function 获取角色权限数据
 * @author Eric
 * @date 2018-05-28
 * @param roleid
 */

router.post('/getroleauthlist', function (req, res) {
  let roleid = req.body.roleid
  let params = {
    roleid: roleid
  }
  if (roleid) {
        // 根据角色id查询对应权限
      roleauth.find(params).then(record => {
      if (record.length > 0) {
          //查询所有权限并匹配当前角色的权限，新增url字段
        /*  let newrecord=JSON.parse(JSON.stringify(record))
          auth.find({},null,{sort: {sortid: 1}},function (err,results) {
            if(results.length>0)
            {
                newrecord.forEach(function(item){
                    results.forEach(function (item2) {
                        if(item.authid===item2.authid)
                        {
                            item.authurl=item2.authurl
                        }

                    })
                })
                res.send(util.reObj(0,'success',newrecord))
            }
          })

*/
          res.send(util.reObj(0,'success',record))
      } else {
          res.send(util.reObj(-1,'not exist'))
      }
    }).catch(err => {
          res.send(util.reObj(-1,'failed',err))
    })
  } else {
      res.send(util.reObj(-1,'roleid不能为空'))
  }

})


/**
 * @function 配置角色权限数据（先删除后增加）
 * @author Eric
 * @date 2018-07-06
 * @param optype,roleid,authdata:[{authid:'',authid:'',...}]
 */
router.post('/setroleauth', function (req, res) {

  let roleid = req.body.roleid
  let authdata = req.body.authdata;
  let delparam = {roleid: roleid}
  if (typeof authdata === 'string')
    authdata = JSON.parse(authdata)

    roleauth.remove(delparam).then(record => {
        async.map(authdata, (item, callback) => {
            let authid = item.authid
            let params = {
                roleid: roleid,
                authid: authid,
            }
            const newObj = new roleauth(params);
            newObj.save( (err, result)=>{
                if(err){
                    callback(null, util.reObj(0, 'setroleauth success', result))
                }else{
                    console.log('setroleauth:'+err)
                    callback(null, util.reObj(-1, 'setroleauth error', err));
                }
            })
        }, (err, results) => {
            if (!err) {
                res.send(results)
            } else {
                res.send(util.reObj(-1, 'del setroleauth faild', err))
            }
        })
    }).catch(err => {
        res.send(util.reObj(-1, 'del setroleauth faild', err))
    });

})

module.exports = router;
